package com.demo.netty;


import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

@Slf4j
public class NettyFutureDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        sync();
        addListener();
    }

    private static void sync() throws ExecutionException, InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        EventLoop loop = group.next();
        Future<Integer> future = loop.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                Thread.sleep(500);
                log.info("loop inside");
                return 0;
            }
        });

        log.info("wait result");
        Integer result = future.get();
        log.info("result:{}", result);
    }

    private static void addListener() {
        NioEventLoopGroup group = new NioEventLoopGroup();
        EventLoop loop = group.next();
        Future<Integer> future = loop.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                Thread.sleep(500);
                log.info("loop inside");
                return 0;
            }
        });

        log.info("wait result");
        future.addListener(new GenericFutureListener<Future<? super Integer>>() {
            @Override
            public void operationComplete(Future<? super Integer> future) throws Exception {
                //get() 会阻塞， getNow() 不会
                log.info("result:{}", future.getNow());
            }
        });

    }

}
